package com.ydc.ln.tutorial.net;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.InputStreamReader;

public class ScanIp03Test {
    public static void main(String[] args) {
        while (NetConst.ip3 < 256 && NetConst.ip4 < 256) {
            Thread scanner = new ScanThread2(NetConst.ip3, NetConst.ip4);
            scanner.start();
            NetConst.ip4 += NetConst.ipCount;
            if (NetConst.ip4 > 255) {
                NetConst.ip3++;
                NetConst.ip4 = 0;
            }
        }
    }
}


class ScanThread2 extends Thread {
    int ip3;
    int ip4;

    public ScanThread2(int ip3, int ip4) {
        this.ip3 = ip3;
        this.ip4 = ip4;
        System.out
                .println(Thread.currentThread() + " scanning from " + ip3 + "."
                        + ip4 + " to " + ip3 + "."
                        + (ip4 + NetConst.ipCount));
    }

    private boolean checkIP(String ip) throws Exception {
        Runtime runtime = Runtime.getRuntime();
        String cmd = "ping " + ip;
        Process proc = runtime.exec(cmd);
        BufferedReader theReader =
                new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String infor = theReader.readLine();
        boolean alive = false;
        while (infor != null) {
            // System.out.println(infor);
            if (infor.startsWith("Reply from")) {
                alive = true;
                break;
            } else if (infor.startsWith("Request timed out")) {
                break;
            }
            infor = theReader.readLine();
        }
        theReader.close();
        proc.destroy();
        return alive;
    }

    public void run() {
        FileWriter writer = null;
        try {
            writer = new FileWriter("ip_alive.txt");
        } catch (Exception e) {
        }

        for (int i = 0; i < NetConst.ipCount; i++) {
            try {
                if (ip3 > 255 || ip3 < 0) {
                    ip3 = 255;
                }
                if (ip4 > 255 || ip4 < 0) {
                    ip4 = 255;
                }
                String ip =
                        NetConst.ip1 + "." + NetConst.ip2 + "." + ip3
                                + "." + ip4;
                boolean alive = checkIP(ip);
                if (alive) {
                    System.out.println(ip + " is alive ");
                    writer.write(ip);
                    writer.flush();
                } else {
                    System.out.println(ip + " is dead ");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            ip4++;
        }
        try {
            writer.close();
        } catch (Exception e) {
        }
    }
}
